# -*- coding: UTF-8 -*-
# from django.shortcuts import render
from queue import Queue  # 实现收藏夹的队列功能
from branch.dataCheck import DataCheck, WechatApi
from django.core.serializers.json import json
from genericpath import exists
from colorama import reinit
from django.http import JsonResponse
import os
import pdb
import json
from user.models import *
from branch.models import *
from report.models import *
import logging
logger = logging.getLogger("userlog")
logger_request = logging.getLogger("django.request")

dataCheck = DataCheck()


def test(request, *args, **kwargs):
    """
    @url:
        /report/test
    """
    data = {
        "code": 0,
        "msg": "report views success",
    }
    # pdb.set_trace()
    return JsonResponse(data)


def submitReport(request, *args, **kwargs):
    """
        url    : /report/submitreport/
        method : POST

    :param request:
                token: data.token,  //用户秘钥
                reportTime: data.reportTime,
                reportType: data.reportType,
                html: data.html,
                devPeo
                reportId

    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息
    """
    form = request.checkForm
    requestParam = form.cleaned_data
    # 验证token
    # pdb.set_trace()
    checkResponse = dataCheck.tokenCheck(requestParam)
    if not checkResponse[0]:
        data = {
            'code': 1,
            'msg': checkResponse[1],
            'requestParam': requestParam,
        }
        return JsonResponse(data)
    # 单条数据更新 个人信息
    user = dataCheck.getUser(requestParam)
    name, stuNum = requestParam['devPeo'].split('-')
    devPeo = UserInfo.objects.filter(stuNum=stuNum, name=name).first().zsdylist
    report = ReportInfo.objects.filter(id=requestParam['reportId'])
    if len(report) != 0:  # 如果之前有数据，则更新数据
        report = report[0]
        report.html = requestParam['html']
        report.devPeo = devPeo
        report.isSubmit = True
        report.isDone = False
        report.reportAuthor = user.name+'-'+requestParam['reportType']
        report.save()
    else:
        ReportInfo.objects.create(
            author=user,
            reportType=requestParam['reportType'],
            reportTime=requestParam['reportTime'],
            html=requestParam['html'],
            devPeo=devPeo,
            isSubmit=True,
            reportAuthor=user.name+'-'+requestParam['reportType'],
        )
    data = {
        'code': 0,
        'msg': 'success',
    }
    return JsonResponse(data, json_dumps_params={'ensure_ascii': False})


def submitCheck(request, *args, **kwargs):
    """
        url    : /report/submitcheck/
        method : POST

    :param request:
            token: data.token,  //用户秘钥
            comment:data.comment,
            correctHtml:data.correctHtml,
            reportId:data.reportId,

    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息
    """
    form = request.checkForm
    requestParam = form.cleaned_data
    # 验证token
    # pdb.set_trace()
    checkResponse = dataCheck.tokenCheck(requestParam)
    if not checkResponse[0]:
        data = {
            'code': 1,
            'msg': checkResponse[1],
            'requestParam': requestParam,
        }
        return JsonResponse(data)
    # 单条数据更新 个人信息
    user = dataCheck.getUser(requestParam)
    report = ReportInfo.objects.filter(id=requestParam['reportId'])
    # pdb.set_trace()
    if len(report) == 0:
        data = {
            'code': 1,
            'msg': '报告不存在',
        }
    else:
        report = report.first()
        isDone = False
        if requestParam['isDone'] == 'yes':
            isDone = True
        report.comment = requestParam['comment']
        report.correctHtml = requestParam['correctHtml']
        report.isCorrect = True
        report.isDone = isDone
        report.save()
        data = {
            'code': 0,
            'msg': 'success',
        }
    return JsonResponse(data, json_dumps_params={'ensure_ascii': False})


def getReportList(request, *args, **kwargs):
    """
        url    : /report/getreportlist/
        method : POST

    :param request:
                token: data.token,  //用户秘钥
                reportTime: data.reportTime,
                reportType: data.reportType,
                html: data.html,
                devPeo
                reportId

    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息
              'reportlist'
    """
    form = request.checkForm
    requestParam = form.cleaned_data
    # 验证token
    # pdb.set_trace()
    checkResponse = dataCheck.tokenCheck(requestParam)
    if not checkResponse[0]:
        data = {
            'code': 1,
            'msg': checkResponse[1],
            'requestParam': requestParam,
        }
        return JsonResponse(data)
    user = dataCheck.getUser(requestParam)
    reports = ReportInfo.objects.filter(author=user).order_by("-reportTime")
    reportList = []
    for report in reports:
        reportList.append(
            {
                'id': report.id,
                'reportType': report.reportType,
                'reportTime': report.reportTime,
                'isSubmit': report.isSubmit,
                'isDone': report.isDone,
                'isCorrect': report.isCorrect,
                'isShow': True,
                'author': user.name,
                'devPeo': report.devPeo.name.name+'-'+report.devPeo.name.stuNum,
            }
        )
    data = {
        'code': 0,
        'msg': 'success',
        'reportlist': reportList,
    }
    return JsonResponse(data, json_dumps_params={'ensure_ascii': False})


def getCheckList(request, *args, **kwargs):
    """
        url    : /report/getckeck/
        method : POST

    :param request:
                token: data.token,  //用户秘钥

    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息
              'reportlist'
    """
    form = request.checkForm
    requestParam = form.cleaned_data
    # 验证token
    # pdb.set_trace()
    checkResponse = dataCheck.tokenCheck(requestParam)
    if not checkResponse[0]:
        data = {
            'code': 1,
            'msg': checkResponse[1],
            'requestParam': requestParam,
        }
        return JsonResponse(data)
    user = dataCheck.getUser(requestParam)
    devPeo = ZSDYList.objects.filter(name=user).first()  # 根据用户查找正式党员
    reports = ReportInfo.objects.filter(
        devPeo=devPeo).order_by("reportTime")  # 根据正式党员查找报告
    reportList = []
    for report in reports:
        if not report.isDone:  # 筛选出来需要批改的
            reportList.append(
                {
                    'id': report.id,
                    'reportType': report.reportType,
                    'reportTime': report.reportTime,
                    'isSubmit': report.isSubmit,
                    'isDone': report.isDone,
                    'isCorrect': report.isCorrect,
                    'isShow': True,
                    'author': report.author.name,
                }
            )
    data = {
        'code': 0,
        'msg': 'success',
        'checklist': reportList,
    }
    return JsonResponse(data, json_dumps_params={'ensure_ascii': False})


def deleteRP(request, *args, **kwargs):
    """
        url    : /user/delete/
        method : POST

    :param request:
                token: data.token,  //用户秘钥
                reportId

    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息

    """
    form = request.checkForm
    requestParam = form.cleaned_data
    # 验证token
    # pdb.set_trace()
    checkResponse = dataCheck.tokenCheck(requestParam)
    if not checkResponse[0]:
        data = {
            'code': 1,
            'msg': checkResponse[1],
            'requestParam': requestParam,
        }
        return JsonResponse(data)
    user = dataCheck.getUser(requestParam)
    reportId = requestParam['reportId']
    report = ReportInfo.objects.filter(id=reportId, author=user)
    if len(report) == 0:
        data = {
            'code': 1,
            'msg': "report doesn't exist",
        }
    else:
        report = report.first()
        report.delete()
        data = {
            'code': 0,
            'msg': "success",
        }
    return JsonResponse(data, json_dumps_params={'ensure_ascii': False})


def getReportContent(request, *args, **kwargs):
    """
        url    : /user/getcontent/
        method : POST

    :param request:
                token: data.token,  //用户秘钥
                reportId

    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息

    """
    form = request.checkForm
    requestParam = form.cleaned_data
    # 验证token
    # pdb.set_trace()
    checkResponse = dataCheck.tokenCheck(requestParam)
    if not checkResponse[0]:
        data = {
            'code': 1,
            'msg': checkResponse[1],
            'requestParam': requestParam,
        }
        return JsonResponse(data)
    user = dataCheck.getUser(requestParam)
    reportId = requestParam['reportId']
    report = ReportInfo.objects.filter(id=reportId)
    if len(report) == 0:
        data = {
            'code': 1,
            'msg': "report doesn't exist",
        }
    else:
        report = report.first()
        content = {}
        # pdb.set_trace()
        content['comment'] = report.comment
        content['html'] = report.html
        content['correctHtml'] = report.correctHtml
        content['createTime'] = report.createTime
        content['reportTime'] = report.reportTime
        content['reportType'] = report.reportType
        content['devPeo'] = report.devPeo.name.name + \
            '-'+report.devPeo.name.stuNum
        data = {
            'code': 0,
            'msg': "success",
            'content': content,
        }
    # 报告的html需要这样返回
    return JsonResponse(data, json_dumps_params={'ensure_ascii': False})
